from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver, WebElement

from apps.seleuinms import OPEN_URL

from apps.logger_config import logger


class Scripts:
    OPEN_URL_SCRIPT = """
    console.log(arguments);
    window.open(arguments[0], arguments[1])
    """

    PRINT_SCRIPT = """window.print()"""


def click_element(driver: WebDriver, element: WebElement = None):
    if element is not None:
        ele = element
    else:
        ele = driver.find_element(By.NAME, 'body')
    ele.click()


def switch_window(driver: WebDriver, window_handle: str):
    driver.switch_to.window(window_handle)
    click_element(driver)


def open_window(driver: WebDriver, url: str, target: str = None):
    driver.execute_script(Scripts.OPEN_URL_SCRIPT, url, target)


def open_other_window(driver: WebDriver, url: str):
    logger.info(OPEN_URL, url)
    handles = driver.window_handles
    open_window(driver, url)
    after_window_handles = driver.window_handles
    different = after_window_handles[len(handles)]
    driver.switch_to.window(different)
    return different
